package com.zhixing.web.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zhixing.web.common.constant.FieldDefaultValueConstant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dzh
 * @version 1.0.0.05020
 * <p>project: d-blog</p>
 * <p>created time: 2022/05/02 15:17</p>
 * <p>describe: 获取方法参数工具类</p>
 * <p>remarks: </p>
 **/
public class ArgsUtil {

    public static String getParamsToString(ProceedingJoinPoint proceedingJoinPoint) {

        Object[] args = proceedingJoinPoint.getArgs();

        if (args == null) {

            return FieldDefaultValueConstant.NOT_ARGS;
        }

        StringBuilder result = new StringBuilder();

        try {

            for (Object obj : args) {

                if (obj instanceof HttpServletRequest ||
                        obj instanceof HttpServletResponse || obj instanceof MultipartFile) {

                    continue;
                }

                result.append(JSON.toJSONString(obj));
            }

        } catch (JSONException e) {

            return getParams(proceedingJoinPoint);
        }

        return result.toString();
    }

    private static String getParams(ProceedingJoinPoint proceedingJoinPoint) {

        Object[] args = proceedingJoinPoint.getArgs();

        JSONObject params = new JSONObject();

        Signature signature = proceedingJoinPoint.getSignature();

        MethodSignature methodSignature = (MethodSignature) signature;

        for (int i = 0; i < methodSignature.getParameterNames().length; i++) {

            if (args[i] instanceof HttpServletRequest ||
                    args[i] instanceof HttpServletResponse ||
                    args[i] instanceof MultipartFile) {

                continue;
            }

            params.put(methodSignature.getParameterNames()[i], args[i]);
        }

        return params.toJSONString();
    }

}